package controller

import (
	"bytes"
	"fmt"
	"minissh/common"
	"minissh/config"
	"minissh/flags"
	"minissh/global"
	"sync"
)

func MiniSsh() {
	//chs := make([]chan common.SSHResult, 3)
	if flags.GetArgs().ConfigFile != "" {
		wg := sync.WaitGroup{}
		for _, ip := range config.GetCfg().Host.Ip {
			//fmt.Println(i, ip)
			wg.Add(1)
			conf := &common.Conf{
				User:            config.GetCfg().Host.Username,
				Password:        config.GetCfg().Host.Password,
				Host:            ip,
				Key:             config.GetCfg().Host.Key,
				Port:            config.GetCfg().Host.Port,
				CipherList:      config.GetCfg().Host.CipherList,
				KeyExchangeList: config.GetCfg().Host.KeyExchangeList,
			}

			//fmt.Println("conf:", conf)
			//
			//fmt.Println("ccccc", conf, flags.GetArgs().Cmds)
			//
			//chs[i] = make(chan common.SSHResult, 1)
			//common.DoSSH(&conf, flags.GetArgs(), chs[i])
			//fmt.Println(conf)
			go func(c *common.Conf) {
				defer wg.Done()
				ExecCmd(c)
			}(conf)
		}
		wg.Wait()
	} else {
		c := &common.Conf{
			User:            flags.GetArgs().Username,
			Password:        flags.GetArgs().Password,
			Host:            flags.GetArgs().Hosts,
			Key:             flags.GetArgs().Key,
			Port:            flags.GetArgs().Port,
			CipherList:      global.SplitString(flags.GetArgs().Ciphers),
			KeyExchangeList: global.SplitString(flags.GetArgs().KeyExchanges),
		}
		ExecCmd(c)
	}
}

func ExecCmd(c *common.Conf) {
	session, err := common.Connect(c)
	if err != nil {
		fmt.Println(err)
		return
	}

	defer session.Close()

	var sshstdout bytes.Buffer
	session.Stdout = &sshstdout

	err = session.Run(flags.GetArgs().Cmds)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Printf("%c[0;0;36m%s%c[0m\n", 0x1B, c.Host, 0x1B)
	fmt.Print(sshstdout.String())
}
